package edu.wy.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import edu.wy.entity.Users;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static edu.wy.utils.RedisContans.LOGIN_CODE_KEY;
import static edu.wy.utils.RedisContans.LOGIN_USER_TTL;

/**
 * @author jianhong_ran
 */

@Component
public class UserUtils {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    public String storeUserInfoInRedis(Users user, String token) {
        // 将User对象转换为Map
        Map<String, Object> beanToMap = BeanUtil.beanToMap(user, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) ->
                                fieldValue == null ? "" : fieldValue.toString())); // 添加空值检查

        // 存储用户信息到Redis
        stringRedisTemplate.opsForHash().putAll(LOGIN_CODE_KEY + token, beanToMap);
        // 设置token有效期
        stringRedisTemplate.expire(LOGIN_CODE_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);

        // 返回token
        return token;
    }

    public Users getUserInfoFromRedis(String token) {
        // 从Redis中获取用户信息
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_CODE_KEY + token);

        if (userMap.isEmpty()) {
            // 如果未找到用户信息，返回null
            return null;
        }

        // 将Map转换为User对象

        return BeanUtil.mapToBean(userMap, Users.class, true, CopyOptions.create());
        
    }
}
